package com.wonder.netty;




import com.wonder.app.domain.BusStallProptection;
import com.wonder.app.domain.Scan;
import com.wonder.app.mapper.BusStallProptectionMapper;
import com.wonder.app.mapper.ScanDao;
import com.wonder.app.vo.StallVo;
import com.wonder.global.Global;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 * I/O数据读写处理类
 *
 */
@ChannelHandler.Sharable
@Component
public class BootNettyChannelInboundHandlerAdapter extends ChannelInboundHandlerAdapter{

    public static List<String> msgList = new ArrayList<>();



    public static BootNettyChannelInboundHandlerAdapter bootNettyChannelInboundHandlerAdapter;

    //1.正常注入[记得主类也需要使用@Component注解]
    @Autowired
    BusStallProptectionMapper busStallProptectionMapper;

    @Autowired
    private ScanDao scanDao;

    //2.初始化构造方法一定要有
    public BootNettyChannelInboundHandlerAdapter(){

    }
    //3.容器初始化的时候进行执行-这里是重点
    @PostConstruct
    public void init() {
        bootNettyChannelInboundHandlerAdapter = this;
        bootNettyChannelInboundHandlerAdapter.busStallProptectionMapper = this.busStallProptectionMapper;
        bootNettyChannelInboundHandlerAdapter.scanDao = this.scanDao;
    }
    /**
     * 从服务端收到新的数据时，这个方法会在收到消息时被调用
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg == null){
            return;
        }

        ByteBuf buf = (ByteBuf) msg;
        byte[] bytes = new byte[buf.readableBytes()];
        // 复制内容到字节数组bytes
        buf.readBytes(bytes);

        String str = new String(bytes);
        System.out.println(str);
        String[] split = str.split("\r\n");
//        for (String tray : split){
//            //截取出员工编号和流水号
////            String userId = tray.substring(0, str.indexOf(","));//员工编号
////            String trayNum = tray.substring(str.indexOf(",") + 1);//流水号
//            if (msgList.contains(tray)){
//                continue;
//            }
//            BootNettyClientChannel bootNettyClientChannel = BootNettyClientChannelCache.get("clientId:"+ctx.channel().id().toString());
//            if(bootNettyClientChannel != null){
//                //修改追溯码的状态
////                bootNettyChannelInboundHandlerAdapter.scanDao.insert(scan);
//            }
//            bootNettyClientChannel.setLast_data(msg.toString());
//            msgList.add(tray);
//        }
        }




        // 将接收到的数据转为字符串，此字符串就是客户端发送的字符串
//        String s = NettyConnectHelper.bytesToHexFun(bytes);
//        String receiveStr = NettyConnectHelper.receiveHexToString(bytes);
//        StallVo stallVo = NettyConnectHelper.receiveHexToObj(bytes);

//        BootNettyClientChannel bootNettyClientChannel = BootNettyClientChannelCache.get("clientId:"+ctx.channel().id().toString());
//        if(bootNettyClientChannel != null){
//            //判断指定状态的数据进行处理
//            if(Global.getInstance().abnormalCarStatusList.contains(stallVo.getCarStatus())){
//                BusStallProptection busStallProptection = BusStallProptection.builder()
//                        .carNumber(stallVo.getCarNumber())
//                        .carState(stallVo.getCarStatus())
//                        .stallScope(stallVo.getAreaNumber())
//                        .rawData(receiveStr)
//                        .uploadTime(new Date())
//                        .build();
//                //插入数据库
//                bootNettyChannelInboundHandlerAdapter.busStallProptectionMapper.insert(busStallProptection);
//            }
//            bootNettyClientChannel.setLast_data(msg.toString());
//        }


    /**
     * 从服务端收到新的数据、读取完成时调用
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws IOException {
        ctx.flush();
    }

    /**
     * 当出现 Throwable 对象才会被调用，即当 Netty 由于 IO 错误或者处理器在处理事件时抛出的异常时
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws IOException {
        System.out.println("exceptionCaught");
        cause.printStackTrace();
        ctx.close();//抛出异常，断开与客户端的连接
    }

    /**
     * 客户端与服务端第一次建立连接时 执行
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception, IOException {
        super.channelActive(ctx);
        InetSocketAddress inSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = inSocket.getAddress().getHostAddress();
        System.out.println(clientIp);
    }

    /**
     * 客户端与服务端 断连时 执行
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception, IOException {
        System.out.println("断开连接");
        super.channelInactive(ctx);
        InetSocketAddress inSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = inSocket.getAddress().getHostAddress();
        ctx.close(); //断开连接时，必须关闭，否则造成资源浪费
        System.out.println("channelInactive:"+clientIp);
        Global.getInstance().canTcpConnected = false;
        //断开连接后重连

    }




}